package com.llsydn.beijingnews.menudetailpager.tabdetailpager;

import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.handmark.pulltorefresh.library.extras.SoundPullEventListener;
import com.llsydn.beijingnews.R;
import com.llsydn.beijingnews.base.BaseMenuDetailPager;
import com.llsydn.beijingnews.common.Constants;
import com.llsydn.beijingnews.domain.NewsBean;
import com.llsydn.beijingnews.domain.TabDetailBean;
import com.llsydn.beijingnews.util.CacheUtils;
import com.llsydn.beijingnews.util.LogUtil;
import com.llsydn.beijingnews.view.HorizontalScollViewPager;
import org.xutils.common.Callback;
import org.xutils.common.util.DensityUtil;
import org.xutils.http.RequestParams;
import org.xutils.image.ImageOptions;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.List;

/**
 * @author lilinshen
 * @title 页签详情页面
 * @description 请填写相关描述
 * @date 2018/10/26 9:26
 */
public class TopicDetailPager extends BaseMenuDetailPager {
    @ViewInject(R.id.viewpager)
    private HorizontalScollViewPager viewpager;
    @ViewInject(R.id.tv_title)
    private TextView tv_title;
    @ViewInject(R.id.ll_point_group)
    private LinearLayout ll_point_group;

    // 之前点高亮显示的位置
    private int prePosition;
    // 页面的数据
    private final NewsBean.DataBean.ChildrenBean childrenData;
    // 页面请求的地址url
    private String url;
    // 顶部轮播图的数据
    List<TabDetailBean.DataBean.TopnewsBean> topnews;
    // 新闻列表数据集合
    List<TabDetailBean.DataBean.NewsBean> news;
    // x.image默认图片
    public ImageOptions imageOptions;
    // 加载更多的url
    private String moreUrl;
    // 是否加载更多
    private boolean isLoadMore;
    private MyListViewAdapter adapter;
    private PullToRefreshListView mPullRefreshListView;
    private ListView listview;

    public TopicDetailPager(Context context, NewsBean.DataBean.ChildrenBean childrenData) {
        super(context);
        this.childrenData = childrenData;

        imageOptions = new ImageOptions.Builder()
                .setSize(DensityUtil.dip2px(100), DensityUtil.dip2px(100))
                .setRadius(DensityUtil.dip2px(5))
                .setCrop(true)
                .setImageScaleType(ImageView.ScaleType.CENTER_CROP)
                .setLoadingDrawableId(R.drawable.news_pic_default)
                .setFailureDrawableId(R.drawable.news_pic_default)
                .build();
    }


    @Override
    public View initView() {
        View view = View.inflate(context, R.layout.topic_detail_pager, null);

        mPullRefreshListView = view.findViewById(R.id.pull_refresh_list);
        listview = mPullRefreshListView.getRefreshableView();

        // 添加声音特效
        SoundPullEventListener<ListView> soundListener = new SoundPullEventListener<ListView>(context);
        soundListener.addSoundEvent(PullToRefreshBase.State.PULL_TO_REFRESH, R.raw.pull_event);
        soundListener.addSoundEvent(PullToRefreshBase.State.PULL_TO_REFRESH, R.raw.reset_sound);
        soundListener.addSoundEvent(PullToRefreshBase.State.PULL_TO_REFRESH, R.raw.refreshing_sound);
        mPullRefreshListView.setOnPullEventListener(soundListener);

        x.view().inject(this, view);
        View topNewsView = View.inflate(context, R.layout.topnews, null);
        x.view().inject(this, topNewsView);

        // 把顶部轮播图部分视图，以头的方式添加到listview中
        listview.addHeaderView(topNewsView);

        // 设置下来刷新
        mPullRefreshListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            // 下拉刷新
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                // 重新请求数据
                getDataFromWebServer();
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                if (TextUtils.isEmpty(moreUrl)) {
                    Toast.makeText(context, "没有更多数据", Toast.LENGTH_SHORT).show();
                    mPullRefreshListView.onRefreshComplete();
                } else {
                    getMoreDataFromWebServer();
                }
            }
        });

        return view;
    }


    /**
     * 加载更多数据
     */
    private void getMoreDataFromWebServer() {
        RequestParams params = new RequestParams(moreUrl);
        params.setConnectTimeout(10000);
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                LogUtil.e("加载更多请求成功==" + result);
                // 解析数据
                isLoadMore = true;
                processData(result);
                // 隐藏加载更多控件
                mPullRefreshListView.onRefreshComplete();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                // LogUtil.e("页面数据请求失败==" + ex.getMessage());
                LogUtil.e("加载更多请求失败");
                // 隐藏加载更多控件
                mPullRefreshListView.onRefreshComplete();
            }

            @Override
            public void onCancelled(CancelledException cex) {
                LogUtil.e("加载更多请求取消==" + cex.getMessage());
            }

            @Override
            public void onFinished() {
                LogUtil.e("加载更多请求结束");
            }
        });

    }


    @Override
    public void initData() {
        super.initData();
        url = Constants.BASE_URL + childrenData.getUrl();
        LogUtil.e(childrenData.getTitle() + "联网地址：" + url);
        String saveJson = CacheUtils.getString(context, url);
        if (!TextUtils.isEmpty(saveJson)) {
            processData(saveJson);
        }
        // 联网请求数据
        getDataFromWebServer();
    }

    /**
     * 解析json数据
     *
     * @param json
     */
    private void processData(String json) {
        TabDetailBean bean = new Gson().fromJson(json, TabDetailBean.class);
        moreUrl = "";
        if (!TextUtils.isEmpty(bean.getData().getMore())) {
            moreUrl = Constants.BASE_URL + bean.getData().getMore();
        } else {
            moreUrl = "";
        }
        LogUtil.e("加载更多的地址：" + moreUrl);

        // 默认和加载更多
        if (!isLoadMore) {
            // 默认
            // 顶部轮播图的数据
            topnews = bean.getData().getTopnews();

            // 设置viewpager的adapter
            viewpager.setAdapter(new MyTabDetailPagerAdapter());

            // 添加红点
            addPoint();

            // 监听页面的变化设置红点和标题
            viewpager.addOnPageChangeListener(new MyOnPageChangeListener());
            tv_title.setText(topnews.get(prePosition).getTitle());

            // 准备listview的集合数据
            news = bean.getData().getNews();

            // 设置listview的adapter
            adapter = new MyListViewAdapter();
            listview.setAdapter(adapter);
        } else {
            // 加载更多
            isLoadMore = false;
            List<TabDetailBean.DataBean.NewsBean> morenews = bean.getData().getNews();

            // 添加到原来集合中，并刷新适配器
            news.addAll(morenews);
            adapter.notifyDataSetChanged();
        }
    }

    /**
     * listview的apapter
     */
    class MyListViewAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return news.size();
        }

        @Override
        public Object getItem(int position) {
            return news.get(position);
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder viewHolder;
            if (null == convertView) {
                convertView = View.inflate(context, R.layout.item_tabdetail_pager, null);
                viewHolder = new ViewHolder();
                viewHolder.iv_icon = convertView.findViewById(R.id.iv_icon);
                viewHolder.tv_title = convertView.findViewById(R.id.tv_title);
                viewHolder.tv_time = convertView.findViewById(R.id.tv_time);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }
            // 设置值给子view
            TabDetailBean.DataBean.NewsBean newsBean = news.get(position);
            String imageUrl = Constants.BASE_URL + newsBean.getListimage();
            // 联网请求图片，并设置默认图片
            x.image().bind(viewHolder.iv_icon, imageUrl, imageOptions);
            viewHolder.tv_title.setText(newsBean.getTitle());
            viewHolder.tv_time.setText(newsBean.getPubdate());
            return convertView;
        }
    }

    static class ViewHolder {
        ImageView iv_icon;
        TextView tv_title;
        TextView tv_time;
    }

    /**
     * 监听viewpager，监听页面的变化设置红点和标题
     */
    class MyOnPageChangeListener implements ViewPager.OnPageChangeListener {

        @Override
        public void onPageScrolled(int i, float v, int i1) {

        }

        @Override
        public void onPageSelected(int i) {
            // 设置文本
            tv_title.setText(topnews.get(i).getTitle());
            // 红点高亮
            ll_point_group.getChildAt(prePosition).setEnabled(false);
            ll_point_group.getChildAt(i).setEnabled(true);
            prePosition = i;
        }

        @Override
        public void onPageScrollStateChanged(int i) {

        }
    }

    /**
     * 图片的adapter
     */
    class MyTabDetailPagerAdapter extends PagerAdapter {

        @Override
        public int getCount() {
            return topnews.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object o) {
            return view == o;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            ImageView imageView = new ImageView(context);
            imageView.setBackgroundResource(R.drawable.home_scroll_default);
            imageView.setScaleType(ImageView.ScaleType.FIT_XY); //图片拉伸
            container.addView(imageView);
            // 联网请求图片
            String imageUrl = Constants.BASE_URL + topnews.get(position).getTopimage();
            LogUtil.e("联网请求的图片url=" + imageUrl);
            // x.image().bind(imageView, imageUrl);
            // 改用glide方式请求图片
            Glide.with(context)
                    .load(imageUrl)
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .into(imageView);
            return imageView;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }
    }

    /**
     * 添加红点
     */
    private void addPoint() {
        ll_point_group.removeAllViews();
        for (int i = 0; i < topnews.size(); i++) {
            ImageView imageView = new ImageView(context);
            imageView.setBackgroundResource(R.drawable.point_selector);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(DensityUtil.dip2px(5), DensityUtil.dip2px(5));
            if (i == 0) {
                imageView.setEnabled(true);
            } else {
                imageView.setEnabled(false);
                params.leftMargin = DensityUtil.dip2px(8);
            }
            imageView.setLayoutParams(params);
            ll_point_group.addView(imageView);
        }
    }

    /**
     * 联网请求数据
     */
    private void getDataFromWebServer() {
        RequestParams params = new RequestParams(url);
        params.setConnectTimeout(10000);
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                LogUtil.e("页面数据请求成功==" + result);
                // 缓存数据
                CacheUtils.putString(context, url, result);
                // 解析数据
                processData(result);
                // 隐藏下拉刷新控件-更新时间，并重新显示数据
                mPullRefreshListView.onRefreshComplete();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                // LogUtil.e("页面数据请求失败==" + ex.getMessage());
                LogUtil.e("页面数据请求失败");
                // 隐藏下拉刷新控件-不更新时间
                mPullRefreshListView.onRefreshComplete();
            }

            @Override
            public void onCancelled(CancelledException cex) {
                LogUtil.e("页面数据请求取消==" + cex.getMessage());
            }

            @Override
            public void onFinished() {
                LogUtil.e("页面数据请求结束");
            }
        });
    }
}
